package v3

import (
	"net/http"
	"strings"
)

type Routable interface {
	Route(method string, pattern string, handlerFunc func(c *Context))
}

type Handler interface {
	ServeHTTP(c *Context)
	Routable
}

type HandlerBasedOnMap struct {
	handlers map[string]func(c *Context)
}

func (h *HandlerBasedOnMap) Route(method string, pattern string, handlerFunc func(c *Context)) {
	key := h.Key(method, pattern)
	h.handlers[key] = handlerFunc
}

func (h *HandlerBasedOnMap) ServeHTTP(c *Context) {
	key := h.Key(c.R.Method, c.R.URL.Path)
	if handler, ok := h.handlers[key]; ok {
		handler(NewContext(c.W, c.R))
	} else {
		c.W.WriteHeader(http.StatusNotFound)
		c.W.Write([]byte("Not Found"))
	}
}

func (h *HandlerBasedOnMap) Key(method string, pattern string) string {
	return strings.ToLower(method) + "#" + pattern
}

// 这里主要是确认 HandlerBasedOnMap 方法实现了 Handler 所有方法
var _ Handler = &HandlerBasedOnMap{}

func NewHandlerBaseOnMap() Handler {
	return &HandlerBasedOnMap{
		handlers: make(map[string]func(c *Context), 10),
	}
}
